module.exports = (sequelize, DataTypes) => {
  const Category = sequelize.define('Category', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true,
      comment: '主键ID'
    },
    name: {
      type: DataTypes.STRING(100),
      allowNull: false,
      comment: '分类名称'
    },
    slug: {
      type: DataTypes.STRING(100),
      allowNull: false,
      unique: true,
      comment: 'URL友好标识'
    },
    description: {
      type: DataTypes.TEXT,
      comment: '分类描述'
    },
    icon: {
      type: DataTypes.STRING(100),
      comment: '分类图标'
    },
    color: {
      type: DataTypes.STRING(7),
      defaultValue: '#3b82f6',
      comment: '分类颜色'
    },
    sortOrder: {
      type: DataTypes.INTEGER,
      defaultValue: 0,
      field: 'sort_order',
      comment: '排序权重'
    },
    parentId: {
      type: DataTypes.INTEGER,
      field: 'parent_id',
      comment: '父分类ID'
    },
    isActive: {
      type: DataTypes.BOOLEAN,
      defaultValue: true,
      field: 'is_active',
      comment: '是否启用'
    }
  }, {
    tableName: 'categories',
    underscored: true,
    timestamps: true,
    createdAt: 'created_at',
    updatedAt: 'updated_at',
    comment: '课程分类表',
    indexes: [
      // 只保留必要的索引，避免重复
      {
        fields: ['parent_id']
      },
      {
        fields: ['is_active', 'sort_order']
      }
    ]
  });

  Category.associate = (models) => {
    // 自关联：父子分类
    Category.belongsTo(models.Category, {
      as: 'parent',
      foreignKey: 'parentId',
      constraints: false  // 避免循环引用问题
    });
    
    Category.hasMany(models.Category, {
      as: 'children',
      foreignKey: 'parentId',
      constraints: false  // 避免循环引用问题
    });
    
    // 与课程的关联
    Category.hasMany(models.Lesson, {
      foreignKey: 'categoryId',
      as: 'lessons',
      onDelete: 'RESTRICT'  // 防止意外删除有课程的分类
    });
  };

  return Category;
}; 